package com.xiaobao.campusLostFoundAfter.controller;

import com.xiaobao.campusLostFoundAfter.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/File")
public class FileController {

    // 文件存储路径，可配置到application.properties中
    private static final String UPLOAD_DIR = "D:/uploads/";
    private static final Logger log = LoggerFactory.getLogger(FileController.class);

    @PostMapping("/upload")
    public Result<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("上传文件不能为空");
        }

        try {
            // 创建存储目录
            File uploadDir = new File(UPLOAD_DIR);
            if (!uploadDir.exists()) {
                // 创建存储目录
                boolean isMkDirsSuccess = uploadDir.mkdirs();
                if (!isMkDirsSuccess) {
                    return Result.error("无法创建上传目录，请检查路径权限");
                }


            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = null;
            if (originalFilename != null) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String fileName = UUID.randomUUID() + fileExtension;

            // 保存文件
            File dest = new File(UPLOAD_DIR + fileName);
            file.transferTo(dest);

            // 返回文件访问URL（实际项目中可能需要根据部署环境调整）
            String fileUrl = "/uploads/" + fileName;
            return Result.success(fileUrl);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return Result.error("文件上传失败");
        }
    }
}